package stanPaysNg

import (
	"bytes"
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"net/http"
)

// 使用私钥对数据进行签名
func signData(data, privateKey string) (string, error) {
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return "", fmt.Errorf("failed to parse private key")
	}

	parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return "", err
	}
	key := parsedKey.(*rsa.PrivateKey)
	hashed := sha256.Sum256([]byte(data))
	signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hashed[:])
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(signature), nil
}

// 发送POST请求
func sendPostRequest(url string, request interface{}) ([]byte, error) {
	jsonData, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	fmt.Println("payment request:", string(jsonData))
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("result is not 200")
	}
	return io.ReadAll(resp.Body)

}

func verifySign(data, sign, pubKeyStr string) (bool, error) {
	block, _ := pem.Decode([]byte(pubKeyStr))
	if block == nil {
		return false, fmt.Errorf("failed to parse public key")
	}

	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return false, err
	}
	rsaPub, ok := pub.(*rsa.PublicKey)
	if !ok {
		return false, fmt.Errorf("not RSA public key")
	}

	hashed := sha256.Sum256([]byte(data))
	signature, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		return false, err
	}

	//fmt.Println("toSignString:", data)
	//fmt.Println("Sign:", sign)
	//fmt.Println("platform public key:", pubKeyStr)
	err = rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, hashed[:], signature)
	return err == nil, err
}
